	#include "precomp.h"
	#include "Player.h"

	Player::Player(const char* image_path, CL_GraphicContext *gc, CL_InputContext *ic, Map *map, char map_sign) 
			: Character(image_path, gc, map, map_sign), _ic(ic)
	{
		_mouse = &_ic->get_mouse();
		_keyboard = &_ic->get_keyboard();

		slotMouseUp = _mouse->sig_key_up().connect(this, &Player::onMouseUp);
		//slotMouseDown = _mouse->sig_key_down().connect(this, &Player::onMouseDown);

		CL_Console::write_line("Player HP: %1", _hp);
	}

	void Player::tick(float delta_time){
		Character::tick(delta_time);

		handle_input(delta_time);
	}

	void Player::draw(){
		Character::draw(_x, _y);
		GameObject::draw(GameObject::center_x, GameObject::center_y);
	}


	void Player::onMouseUp(const CL_InputEvent &key, const CL_InputState &state){
		if(key.id == CL_MOUSE_LEFT){
			_guns[_gun_number]->set_shooting(false);
		}
	}

	void Player::handle_input(float delta_time){
		float m_x = _mouse->get_x(),
			  m_y = _mouse->get_y();
		
		float _atan2  = atan2(m_y - 240 , m_x - 320);
		CL_Angle angle =  CL_Angle::from_radians(_atan2);
		_sprite->set_angle(angle);

		float y_speed = _speed * sin(angle.to_radians()) * delta_time,
			  x_speed = _speed * cos(angle.to_radians()) * delta_time;

		float origi_x = _x,
			  origi_y = _y;

		if(_keyboard->get_keycode(CL_KEY_W)){
			_y += y_speed;
			_x += x_speed;
		}
		if(_keyboard->get_keycode(CL_KEY_S)){
			_y -= y_speed;
			_x -= x_speed;
		}

		CL_Angle left_angle = CL_Angle::from_degrees(angle.to_degrees() - 90);
		y_speed = _speed * sin(left_angle.to_radians()) * delta_time,
		x_speed = _speed * cos(left_angle.to_radians()) * delta_time;

		if(_keyboard->get_keycode(CL_KEY_A)){
			_y += y_speed;
			_x += x_speed;
		}
		if(_keyboard->get_keycode(CL_KEY_D)){
			_y -= y_speed;
			_x -= x_speed;
		}

		for(int i = 0;i < Gun::gun_types;i++){
			if(_keyboard->get_keycode(CL_KEY_1 + i)){
				switch_gun(i);
			}
		}

		if(_keyboard->get_keycode(CL_KEY_R)){
			reload();
		}

		if(_mouse->get_keycode(CL_MOUSE_LEFT)){
			shoot();
		}

		if(collide_map()){
			_x = origi_x;
			_y = origi_y;
		}
		
	}